from pattern.circuit import Control
import weakref, gobject
import os.path, posixpath, urllib
import BaseHTTPServer, SimpleHTTPServer


class HTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

    def notify(self, method):
        s = self.server
        if s is not None and hasattr(s, 'notify'):
            s.notify(self, method, self.path)

    def do_GET(self):
        self.notify("onGet")
        
    def do_POST(self):
        self.notify("onPost")
        

class entry(Control):

    def realize(self, event):
        if not hasattr(event.shape, 'port'):
            event.shape.port = 8080
        if not hasattr(event.shape, 'root'):
            event.shape.root = ""
        self.port = event.shape.port
        self.realized = event
        self.initiate(event)

    def initiate(self, event):
        import thread
        self.server = BaseHTTPServer.HTTPServer(('', self.port),
                                                HTTPRequestHandler)
        shape = weakref.ref(event.shape)
        self.server.getRootPath = lambda: self().getRootPath(shape)
        self.server.notify = self.notify
        self = weakref.ref(self)
        onConnect = lambda source, condition: self().incomingConnection()
        self().watch = gobject.io_add_watch(self().server.socket,\
                                            gobject.IO_IN | gobject.IO_HUP,
                                            onConnect)
        del event

    def incomingConnection(self):
        self.server.handle_request()
        return True

    def shutdown(self, event):
        gobject.source_remove(self.watch)

    def notify(self, handler, method, path):
        self.realized.trail = handler
        self.realized.trail.root = self.realized.shape.root
        bridge = self.acquireInterface(self.realized, method)
        if bridge is not None:
            bridge.push(path)
        self.realized.trail = None
    
